//
//  UploadDataManager.m
//  MeiDa
//
//  Created by zfc on 2019/10/30.
//  Copyright © 2019年 depelec. All rights reserved.
//

#import "UploadDataManager.h"
NSString * const endPoint = @"http://oss-cn-hangzhou.aliyuncs.com";
NSString * const bucketName = @"gas888";


@implementation UploadDataManager

static UploadDataManager *_instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}

//- (instancetype)init{
//    if (self = [super init]) {
//
////        [self setClientWithType:@"images"];
//
//
//    }
//    return self;
//}

+(instancetype) shared {

    return [[self alloc] init];
}

-(id)copyWithZone:(NSZone *)zone {
    return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}


//c从后台获取oss上传参数并创建client  type  -- >  图片:images;文件:files;视频:videos;音频:voices
- (void) setClientWithType:(NSString *)type successBlock:(void (^)(void))successBlock {

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"type"] = type;

    NSString *url = @"/api/tiny-shop/v1/common/file/oss-accredit";
    [[NetWorksTools shared] requestWithMethod:GET url:url params:params successBlock:^(NSDictionary * _Nonnull response) {
        NSDictionary *data = response[@"data"];
                   self.configData = data;
                   self.type = type;
                   //后台服务签名签名
                   id<OSSCredentialProvider> credential = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
                      return data[@"signature"];
               }];
                   self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
                   if (successBlock) {
                       successBlock();
                   }
    } failureBlock:^(NSError * _Nonnull error) {

    }];
//
//    [YQNetworking getWithUrl:url refreshRequest:NO cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
//        } successBlock:^(id response) {
//            NSDictionary *data = response[@"data"];
//            self.configData = data;
//            self.type = type;
//            //后台服务签名签名
//            id<OSSCredentialProvider> credential = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
//               return data[@"signature"];
//        }];
//            self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
//            if (successBlock) {
//                successBlock();
//            }
//        } failBlock:^(NSError *error) {
//
//    }];
}

- (NSString *)getFileName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy/MM/dd";
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSInteger date = [[NSDate date] timeIntervalSince1970]*1000;
    NSInteger last = 100000000 + arc4random() % 90000001;
    NSString *timeNow = [NSString stringWithFormat:@"%zd%zd", date, last];
    NSString *name = [NSString stringWithFormat:@"%@/%@/%@.jpg",self.type, dateStr, timeNow];
    return  name;
}

- (NSString *)getVideoFileName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy/MM/dd";
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSInteger date = [[NSDate date] timeIntervalSince1970]*1000;
    NSInteger last = 100000000 + arc4random() % 90000001;
    NSString *timeNow = [NSString stringWithFormat:@"%zd%zd", date, last];
    NSString *name = [NSString stringWithFormat:@"%@/%@/%@.mp4",self.type, dateStr, timeNow];
    return  name;
}

//视频上传
- (void) uploadVideo:(NSData *)data success:(void (^)(NSString *videoUrl))success {

    if (!self.client) {
        __weak typeof(self) weakSelf = self;

        [self setClientWithType:@"videos" successBlock:^{
            [weakSelf uploadVideo:data success:success];
        }];
        return;
    }

    OSSPutObjectRequest *put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;
    put.uploadingData = data;
    put.contentType = @"video/mp4";

    put.objectKey =  [self getVideoFileName];

    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        [SVProgressHUD showProgress:totalByteSent*1.0/totalBytesExpectedToSend];
    };


    OSSTask * putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSString *url = [NSString stringWithFormat:@"https://gas888.oss-cn-hangzhou.aliyuncs.com/%@", put.objectKey];
            dispatch_async(dispatch_get_main_queue(), ^{
                success(url);
            });
            NSLog(@"视频上传成功 VidoeUrl:%@", url);
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    [putTask waitUntilFinished];


}

//图片上传
- (void) uploadImages:(NSArray *)images success:(void (^)(NSMutableArray *uploadArr))success{

    if (!self.client) {
        __weak typeof(self) weakSelf = self;

        [self setClientWithType:@"images" successBlock:^{
            [weakSelf uploadImages:images success:success];
        }];
        return;
    }

    NSMutableArray * array = [NSMutableArray array];
    OSSPutObjectRequest *put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;

    for (int i = 0; i < images.count; i ++) {
        NSString *fileName =  [self getFileName];
        put.objectKey = fileName;
        UIImage *image = images[i];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        put.uploadingData = imageData;
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
            NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
            
        };

        OSSTask * putTask = [self.client putObject:put];
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSString *url = [NSString stringWithFormat:@"https://gas888.oss-cn-hangzhou.aliyuncs.com/%@", put.objectKey];
                [array addObject:url];
                if (i == images.count - 1) {
                    NSLog(@"图片数组: %@", array);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        success(array);
                    });
                }
                NSLog(@"第%d图片上传成功", i);
            } else {
                NSLog(@"upload object failed, error: %@" , task.error);
            }
            return nil;
        }];
        [putTask waitUntilFinished];
    }

}



@end
